import axios from 'axios';
import { Message } from 'element-ui';

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || 'http://localhost:8089',
  timeout: 5000 // 请求超时时间
});

// 请求拦截器
service.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }
  return config;
}, error => {
  return Promise.reject(error);
});

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code !== 200) {
      Message.error(res.message || '请求错误');
      return Promise.reject(res.message || '请求错误');
    }
    return res;
  },
  error => {
    Message.error(error.message || '请求错误');
    return Promise.reject(error);
  }
);

export default service;